// api接口路径及方法
var models = require('../db');
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var JwtUtil = require('../jwt');
// 我这里的是aes加密密码的可以去掉
// const AesUtil = require('../public/utils/aes');


// 后台接口
var conn = mysql.createConnection(models.mysql);

conn.connect();
var jsonWrite = function (res, ret) {
    if (typeof ret === 'undefined') {
        res.json({
            status: '1',
            message: '操作失败'
        });
    } else {
        res.json({
            message: '成功',
            status: 200,
            data: {
                user_id: ret.insertId
            }
        });
    }
};

// 注册接口
router.post('/register', (req, res) => {
    let params = req.body;
    new Promise((resolve, reject) => {
        conn.query('SELECT * FROM `user` WHERE user_phone='+ params.user_phone +'',function(err,result){
            // console.log('SELECT * FROM `user` WHERE user_phone='+ params.user_phone +'')
            // console.log(err,result)
            if(err) {
                res.send({status:500,message:'注册异常'});
                reject()
            }
            if(!result.length == 0) {
                res.send({status:201,message:'用户已存在'});
                reject()
            } else {
                resolve()
            }
         });
        
    }).then((result) =>{
        console.log(result, 11)
        let sql = 'insert into user(user_phone,user_password) values("'+params.user_phone+'","'+ params.user_password +'")';
        conn.query(sql, [params.user_phone, params.user_password], function (err, result) {
            if (err) {
                console.log("添加失败" + err);
            }
            if (result) {
                jsonWrite(res, result);
            }
        })
    }).catch((err) => {
        console.log(err);
    })
});
// 登录接口
router.post('/login', (req, res) => {
    // var parms = req.query
    // var sql = 'select user_id from user where user_phone=' + parms.user_phone
    // console.log(sql)
    // conn.query(sql, function (err, result) {
    //   if (err) {
    //     console.log(err)
    //   }
    //   if (result) {
    //     // console.log(result)
    //     jsonWrite(res, result);
    //   }
    // })
    var user_phone = req.body.user_phone;
    var pass = req.body.user_password;
    new Promise((resolve, reject) => {
        // 根据用户名查询用户
        // users.findOne({'user_phone':user_phone}).exec((err,result) => {
        //    if(err){
        //        reject(err);
        //    }else{
        //        resolve(result);
        //    }
        // });
        conn.query('SELECT * FROM `user` WHERE user_phone='+ user_phone +'',function(err,result){
            if(err){
                reject(err);
               }else {
                resolve(result);
               }
         });
    }).then((result) => {
        if(result[0].user_id){
            // 密码解密 利用aes
            // var aes = new AesUtil(result.password);
            // var password = aes.deCryto();
            result = result[0]
            if(pass == result.user_password){
                // 登陆成功，添加token验证
                let _id = result.user_id.toString();
                // 将用户id传入并生成token
                let jwt = new JwtUtil(_id);
                let token = jwt.generateToken();
                // 存储token
                conn.query('UPDATE user SET token = ' + '"' + token + '"' + ' WHERE user_id = ' + _id + '',function(err,result){})
                // 将 token 返回给客户端
                res.send({status:200,message:'登陆成功',token:token});
            }else{
                res.send({status:400,message:'账号密码错误'});
            }
        }else{
            res.send({status:404,message:'账号不存在'})
        }
    }).catch((err) => {
        res.send({status:500,message:'账号密码错误'});
    })
  })

module.exports = router;